<template>
  <div>
    <a-spin :spinning="isLoadingOther">
      <a-form ref="formSearchRef" name="advanced_search" class="ant-advanced-search-form" :model="formSearchField">
        <a-row :gutter="24">
          <a-col :span="formSearchColSpan">
            <a-form-item name="account" label="账号">
              <a-input v-model:value="formSearchField.account" placeholder="请输入账号" style="width: 95%;" />
            </a-form-item>
          </a-col>
          <a-col :span="formSearchColSpan">
            <a-form-item name="role_id" label="所属角色">
              <a-select v-model:value="formSearchField.role_id" show-search option-filter-prop="search-value" placeholder="请选择所属角色" style="width: 95%;">
                <a-select-option value="">全部</a-select-option>
                <a-select-option v-for="item in adminRolesList" :key="item.id" :value="item.id" :search-value="item.name">{{ item.name
                  }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="formSearchColSpan" v-if="formSearchExpand">
            <a-form-item name="name" label="姓名">
              <a-input v-model:value="formSearchField.name" placeholder="请输入姓名" style="width: 95%;" />
            </a-form-item>
          </a-col>
          <a-col :span="formSearchColSpan" v-if="formSearchExpand">
            <a-form-item name="status" label="状态">
              <a-select v-model:value="formSearchField.status" placeholder="请选择状态" style="width: 95%;">
                <a-select-option value="">全部</a-select-option>
                <a-select-option v-for="(item, index) in statusMap" :key="index" :value="index">{{ item
                  }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="formSearchColSpan" v-if="formSearchExpand">
            <a-form-item name="position" label="职位">
              <a-input v-model:value="formSearchField.position" placeholder="请输入职位" style="width: 95%;" />
            </a-form-item>
          </a-col>
          <a-col :span="formSearchColSpan">
            <a-button type="primary" html-type="submit" @click="doSearchForm">搜索</a-button>
            <a-button style="margin: 0 8px" @click="resetFormRef">重置</a-button>
            <a-button style="margin-right: 8px" @click="editData(0)"
              v-if="adminCheckOption('admin', 'index', 'add')">新增</a-button>
            <a-button type="link" @click="formSearchExpandChg" v-if="!formSearchExpand">更多搜索</a-button>
            <a-button type="link" @click="formSearchExpandChg" v-if="formSearchExpand">收起</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <a-table bordered :data-source="dataListSource" :columns="dataListColumns" :loading="isLoading"
      @change="dataTableChange" rowKey="id" :pagination="tablePagination">
      <template #bodyCell="{ column, text, record, index }">
        <template v-if="column.dataIndex === 'status_text'">
          <span style="color: red;" v-if="record.status === 2">{{ text }}</span>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <a-tag color="blue" @click="editData(record.id)"
            v-if="adminCheckOption('admin', 'index', 'edit')">编辑</a-tag>
          <a-popconfirm title="确认要禁用吗？" @confirm="onChangeStatus(record.id, 2, index)"
            v-if="adminCheckOption('admin', 'index', 'delete') && record.status === 1">
            <a-tooltip color="red" placement="rightTop">
              <template #title>
                <span>当前是正常状态，点击可删除此数据</span>
              </template>
              <a-tag color="green">删除</a-tag>
            </a-tooltip>
          </a-popconfirm>
          <a-popconfirm title="确认要恢复正常吗？" @confirm="onChangeStatus(record.id, 1, index)"
            v-if="adminCheckOption('admin', 'index', 'undelete') && record.status === 2">
            <a-tooltip color="green" placement="leftTop">
              <template #title>
                <span>当前是已删除状态，点击可重置为正常状态</span>
              </template>
              <a-tag color="red">恢复正常</a-tag>
            </a-tooltip>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { reactive, ref, inject, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue'
import { getAdminList, chgAdminStatus, getAdminRolesListOk } from "@/api/admin"   //引入api
import { useRoute, useRouter } from 'vue-router';
const router = useRouter();

const { adminCheckOption } = inject('adminCheckOption');  // 依赖注入--权限校验函数

const formSearchColSpan = ref(8);  // 搜索--每个搜索项暂用宽度（共24宽度）
const isLoading = ref(false);    // 控制loading
const isLoadingOther = ref(false);    // 控制loading
const formSearchExpand = ref(false);    // 搜索--是否展开更多
const dataListSource = ref([]); // 数据列表
const dataTotal = ref(0);    // 符合条件的数据总数
const formSearchRef = ref();  // 表单搜索,ref对象
const currentPage = ref(1);  // 当前页码
const pageSize = ref(10);      // 每页显示条数
const statusMap = reactive({
  1: '正常',
  2: '已禁用'
});  //状态映射

// 表格分页
const tablePagination = computed(() => ({
  total: dataTotal.value,
  current: currentPage.value,
  pageSize: pageSize.value,
  showTotal: (total, range) => `第 ${range[0]} 至 ${range[1]} 条数据，共 ${total} 条数据`
}));
// 数据列表字段
const dataListColumns = [
  {
    title: '账号',
    dataIndex: 'account',
  },
  {
    title: '姓名',
    dataIndex: 'name',
  },
  {
    title: '职位',
    dataIndex: 'position',
  },
  {
    title: '所属角色',
    dataIndex: 'role_name',
  },
  {
    title: '状态',
    dataIndex: 'status_text',
    width: 80
  },
  {
    title: '操作',
    dataIndex: 'operation',
  },
];
// 表单搜索字段
const formSearchField = reactive({
  page: currentPage.value,  //当前页码（current的值改变后，这里的值不会跟着改变，需要手动赋值）
  limit: pageSize.value,  //每页条数（pageSize的值改变后，这里的值不会跟着改变，需要手动赋值）
  account: '',
  name: '',
  position: '',
  role_id: null,
  status: null,
});

// 表单搜索方法
const doSearchForm = () => {
  currentPage.value = 1;
  getDataList();
};

// 获取接口数据列表
const getDataList = () => {
  isLoading.value = true;

  formSearchField.page = currentPage.value;  //当前页码（current的值改变后，这里的值不会跟着改变，需要手动赋值）
  formSearchField.limit = pageSize.value;  //每页条数（pageSize的值改变后，这里的值不会跟着改变，需要手动赋值）

  getAdminList(formSearchField).then((res) => {
    isLoading.value = false;
    if (res === false) return;

    dataListSource.value = res.data;  //数据列表
    dataTotal.value = res.count;  //总条数

    message.success('获取成功');
  }).catch((rej) => {
    isLoading.value = false;
    message.error('失败：' + rej);
  });
};

// 重置表单搜索
const resetFormRef = () => {
  formSearchRef.value.resetFields();
  currentPage.value = 1;
  getDataList();
};

// 修改数据状态
const onChangeStatus = (id, newStatus, dataIndex) => {
  isLoading.value = true;

  // 提交的数据
  let chgData = {
    id: id,
    status: newStatus
  };

  chgAdminStatus(chgData).then((res) => {
    isLoading.value = false;
    if (res === false) return;

    // 修改数据状态，用于展示修改后的数据
    dataListSource.value[dataIndex].status = newStatus;
    dataListSource.value[dataIndex].status_text = statusMap[newStatus];

    message.success('操作成功');
  }).catch((rej) => {
    isLoading.value = false;
    message.error('失败：' + rej);
  });
};

// 数据列表分页、排序、过滤
const dataTableChange = (pagination, filters, sorter) => {
  currentPage.value = pagination.current;
  getDataList();
};

// 新增、编辑数据
const editData = (id) => {
  router.push({name: 'admin_admin_edit', query: { id: id }});
};

// 搜索--展开/收起更多搜索项
const formSearchExpandChg = () => {
  formSearchExpand.value = !formSearchExpand.value;
};

const adminRolesList = ref([]); // 角色列表
// 获取角色列表
const getAdminRolesList = () => {
  isLoadingOther.value = true;
  getAdminRolesListOk({}).then((res) => {
    isLoadingOther.value = false;
    if (res === false) return;

    adminRolesList.value = res.data;  //角色列表
  });
};


// 页面加载完成后，获取数据列表
onMounted(() => {
  getAdminRolesList();
  getDataList();
})
</script>

<style scoped></style>